cmake_minimum_required(VERSION 3.14)

project(dbus-demo LANGUAGES C CXX)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GLIB REQUIRED glib-2.0 gobject-2.0 gio-unix-2.0)

function(gen_driv XML_FILE)
    get_filename_component(XML_FILE_PATH ${XML_FILE} ABSOLUTE BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
    get_filename_component(DRIV_NAME ${XML_FILE} NAME_WE)
    # string(REGEX REPLACE "\\.xml$" ".h" GEN_HEADER ${XML_FILE})
    # string(REGEX REPLACE "\\.xml$" ".c" GEN_SOURCE ${XML_FILE})
    add_custom_command(
        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${DRIV_NAME}.c ${CMAKE_CURRENT_BINARY_DIR}/${DRIV_NAME}.h
        COMMAND gdbus-codegen
            --generate-c-code=${DRIV_NAME} --c-namespace ${DRIV_NAME}
            --interface-prefix cygia.${DRIV_NAME}.
            ${XML_FILE_PATH}
        DEPENDS ${XML_FILE_PATH}
        WORKING_DIRECTORY ${${CMAKE_CURRENT_BINARY_DIR}}
        COMMENT "generate files: `${DRIV_NAME}.c ${DRIV_NAME}.h`"
    )
endfunction()

function(add_driv TARGET XML_FILE)
    get_filename_component(DRIV_NAME ${XML_FILE} NAME_WE)
    target_sources(${TARGET} PRIVATE
        ${CMAKE_CURRENT_BINARY_DIR}/${DRIV_NAME}.c
        ${CMAKE_CURRENT_BINARY_DIR}/${DRIV_NAME}.h
    )
    target_include_directories(${TARGET} PRIVATE
        ${CMAKE_CURRENT_BINARY_DIR}
    )
endfunction()

gen_driv(battery.xml)

file(GLOB ALL_ITEMS *.c)
foreach(ITEM ${ALL_ITEMS})
    get_filename_component(EXEUTABLE_NAME ${ITEM} NAME_WE)
    message(STATUS "add executable: ${EXEUTABLE_NAME}")
    add_executable(${EXEUTABLE_NAME} ${ITEM})
    add_driv(${EXEUTABLE_NAME} battery.xml)
    target_include_directories(${EXEUTABLE_NAME} PRIVATE ${GLIB_INCLUDE_DIRS})
    target_link_libraries(${EXEUTABLE_NAME}  PRIVATE ${GLIB_LIBRARIES})
endforeach()
